import { followOrUnfollow } from '@/services/consult'
import { sendMobileCode } from '@/services/user'
import type { FollowType } from '@/types/consult'
import type { CodeType } from '@/types/user'
import { type FormInstance, showSuccessToast } from 'vant'
import { ref, onMounted, onUnmounted, type Ref } from 'vue'

export function useWindowSize() {
  const width = ref(0) // 屏幕宽度
  // 设置屏幕宽度
  const setWith = () => (width.value = window.innerWidth)
  onMounted(() => {
    setWith()
    window.addEventListener('resize', setWith)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', setWith)
  })
  return {
    width
  }
}
export function useFollow(type: FollowType = 'doc') {
  const loading = ref(false)
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    try {
      loading.value = true
      await followOrUnfollow(item.id, type)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } catch (error) {
      console.log(error)
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    follow
  }
}
export function useSendMobileCode(
  mobile: Ref<string>,
  type: CodeType = 'login'
) {
  const formRef = ref<FormInstance>()
  const time = ref(0)
  let timer: number
  const send = async () => {
    await formRef.value?.validate('mobile')
    // console.log('ok')
    await sendMobileCode(mobile.value, type)
    showSuccessToast('获取短信验证码成功')
    time.value = 60
    timer = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    // 组件被卸载的时候清除定时器
    onUnmounted(() => {
      time.value && clearInterval(timer)
    })
  }
  return {
    send,
    formRef,
    time
  }
}
